package com.tensquare.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

/**
 * Web 网关过滤器.
 *
 * @author 宫新程
 * @since 2019/3/22 2:11
 */
@Component
public class WebFilter extends ZuulFilter {
  @Override
  public String filterType() {
    return "pre";
  }

  @Override
  public int filterOrder() {
    return 0;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  /** 做请求头的转发，由于经过网关 头信息会丢失 的问题. */
  @Override
  public Object run() throws ZuulException {
    // 得到 Request 上下文：RequestContext
    RequestContext currentContext = RequestContext.getCurrentContext();
    // 得到 request 域
    HttpServletRequest request = currentContext.getRequest();

    String hello = request.getParameter("hello");
    System.out.println("网关获取请求参数：hello：" + hello);

    // 得到头信息
    String header = request.getHeader("Authorization");
    // 判断是否有头信息
    if (header != null && !header.equals("")) {
      // 将头信息向下转发.
      currentContext.addZuulRequestHeader("Authorization", header);
    }
    return null;
  }
}
